#include "msp430G2553.h"                        // device specific header
#include "spi.h"


//------------------------------------------------------------------------------
//  void SPI_init()
// This function initializes the USCI module for master operation.
//-----------------------------------------------------------------------------

void SPI_Init(unsigned char sclk, unsigned char somi, unsigned char simo)
{
	/**
	 * From TIs users manual
	 *
     * The recommended USCI initialization/re-configuration process is:
 	 * 1. Set UCSWRST (BIS.B #UCSWRST,&UCxCTL1)
 	 * 2. Initialize all USCI registers with UCSWRST=1 (including UCxCTL1)
 	 * 3. Configure ports
 	 * 4. Clear UCSWRST via software (BIC.B #UCSWRST,&UCxCTL1)
 	 * 5. Enable interrupts (optional) via UCxRXIE and/or UCxTXIE
 	 */

	// (1)
	UCB0CTL1 = UCSWRST;

	// (2)
    //P1DIR  |= CSN; //Moved to device specific code
    //P1OUT  |= CSN; //Moved to device specific code
  	P1SEL  |= simo+ somi+ sclk;
  	P1SEL2 |= simo+ somi+ sclk;

    // (3) 3-pin, 8-bit SPI master
    UCB0CTL0 |= UCCKPH + UCMSB + UCMST + UCSYNC;
	UCB0CTL1 |= UCSSEL_2;   // SMCLK

	// (4)
	UCB0CTL1 &= ~UCSWRST;
 }

unsigned char SPI_Transfer(unsigned char data)
{
	   UCB0TXBUF = data;

	   while (!(IFG2 & UCB0TXIFG));

	   return UCB0RXBUF;
}

